package com.library.controller;

import com.library.entity.Book;
import com.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import java.util.List;

@Controller
@RequestMapping("/books")
public class BooksController {

    @RequestMapping("/allbooklist")
    public String showbookslist(){



        return "redirect:/books/booklist";
    }

    @Autowired
    private BookService bookService;

    @GetMapping("/booklist")
    public String bookList(Model model) {
        List<Book> books = bookService.getAllBooks();
        model.addAttribute("books", books);
        return "books/booklist";
    }

    @GetMapping("/addbook")
    public String showAddBookForm(Model model) {
        model.addAttribute("book", new Book()); // 初始化一个空的Book对象
        return "books/addbook"; // 返回添加书籍的页面
    }

    @PostMapping("/addbook")
    public String addBook(@ModelAttribute Book book) {
        bookService.addBook(book); // 调用Service层添加书籍
        return "redirect:/books/booklist"; // 添加成功后重定向到书籍列表页面
    }
}
